package com.guigu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.mapper.*;
import com.guigu.pojo.*;
import com.guigu.service.OrdersParticularsService;
import com.guigu.service.PayInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PayInfoServiceimpl extends ServiceImpl<PayInfoMapper, PayInfo> implements PayInfoService {
    @Autowired
    PayInfoMapper payInfoMapper;//出库表
    @Autowired
    PayDetailInfoMapper payDetailInfoMapper;//出库详情表
    @Autowired
    OrdersMapper ordersMapper;//订单表
    @Autowired
    OrdersParticularsMapper ordersParticularsMapper;//订单详情表
    @Autowired
    SupplierSupplyOfGoodsMapper supplierSupplyOfGoodsMapper;//订单详情表
    @Autowired
    WarehouseInfoMapper warehouseInfoMapper;//仓库表
    @Autowired
    WarehouseDetailsInfoMapper warehouseDetailsInfoMapper;//仓库详情表
    //分页查询
    @Override
    public Page<PayInfo> queryAll(PayInfo payInfo, Integer pageno, Integer pagesize) {
        QueryWrapper queryWrapper=new QueryWrapper<PayInfo>();
        //条件查询
        //查询号
        if (payInfo.getTrackingNumber()!=null){
            queryWrapper.eq("tracking_number",payInfo.getTrackingNumber());
        }
        //出库理由
        if (payInfo.getPayType()!=null){
            queryWrapper.eq("pay_type",payInfo.getPayType());
        }
        //审核
        if (payInfo.getIsCheck()!=null){
            queryWrapper.eq("is_check",payInfo.getIsCheck());
        }
        //删除状态
        if (payInfo.getIsDelete()!=null){
            queryWrapper.eq("is_delete",payInfo.getIsDelete());
        }
        Page<PayInfo> page = this.page(new Page<PayInfo>(pageno, pagesize), queryWrapper);
        //循环补全属性
        for(PayInfo p : page.getRecords()){
            queryWrapper=new QueryWrapper<PayDetailInfo>();
            queryWrapper.eq("pay_id",p.getId());
            //补全详情数据
            p.setPayDetailInfoList(payDetailInfoMapper.selectList(queryWrapper));
        }
        return page;
    }

    //根据订单数组ids，循环添加出库表和出库详情表数据，出库表需要审核
    @Override
    public Map addPayInfoandDetailPurchaseInfo(Integer[] ids) {
        Map<String,Object> map=new HashMap();
        //获取所有的仓库，并且设置详情集合
        QueryWrapper queryWrapper=new QueryWrapper<WarehouseInfo>();
        queryWrapper.eq("is_check",1);//审核通过
        queryWrapper.eq("is_delete",0);//未被删除
        List<WarehouseInfo> warehouseInfoList=warehouseInfoMapper.selectList(queryWrapper);
        for(WarehouseInfo w : warehouseInfoList){
            queryWrapper=new QueryWrapper<WarehouseDetailsInfo>();
            queryWrapper.eq("p_id",w.getId());//父id
            w.setWarehouseDetailsInfoList(warehouseDetailsInfoMapper.selectList(queryWrapper));
        }
        //定义出库表id集合和出库详情id集合和订单详情id集合
        List<Integer> payInfoInfoIds=new ArrayList<>();
        List<Integer> payDetailInfoIds=new ArrayList<>();
        List<Integer> ordersParticularsIds=new ArrayList<>();
        //循环订单ids
        if(ids.length>0){
            for(Integer id : ids){
                //根据订单id，获取订单对象和订单详情集合
                Orders orders=ordersMapper.selectById(id);
                queryWrapper=new QueryWrapper<OrdersParticulars>();
                queryWrapper.eq("p_id",orders.getId());//父id
                queryWrapper.eq("is_return",0);//未退货的订单详情
                orders.setOrdersDetails(ordersParticularsMapper.selectList(queryWrapper));
                //将订单表的货物状态设置为【总店发货审核中】
                orders.setGoodsState("g-2");
                ordersMapper.updateById(orders);
                //出库对象
                PayInfo payInfo=new PayInfo();
                //出库理由：发货出库
                payInfo.setPayType(0);
                //查询号：存放订单号
                payInfo.setTrackingNumber(orders.getPId());
                //出库时间：当前时间
                payInfo.setPtime(new Date());
                //审核状态：等待审核
                payInfo.setIsCheck(0);
                //删除状态：正常
                payInfo.setIsDelete(0);
                //进行添加
                Boolean allSpecified=false;
                if(payInfoMapper.insert(payInfo)>0){
                    payInfoInfoIds.add(payInfo.getId());
                    //循环订单详情表添加出库详情表数据
                    for(OrdersParticulars od : orders.getOrdersDetails()){
                        //初始化对象
                        PayDetailInfo payDetailInfo=new PayDetailInfo();
                        payDetailInfo.setPayId(payInfo.getId());
                        //自动匹配仓库id(智能匹配)
                        //循环所有的仓库下面的详情
                        Boolean satisfy=false;
                        for(WarehouseInfo w : warehouseInfoList){
                            for(WarehouseDetailsInfo wd : w.getWarehouseDetailsInfoList()){
                                //检查商品类型
                                if(od.getGId()==wd.getShopId()){
                                    //检查仓库当前库存是否可以满足出库数量，验证方法为：【当前库存-出库数量>=0】
                                    if(wd.getAmount()-od.getBuyQuantity()>=0){
                                        //设置库存
                                        wd.setAmount(wd.getAmount()-od.getBuyQuantity());
                                        //满足出库要求，中断循环
                                        satisfy=true;
                                        //仓库详情id临时存入仓库id属性内
                                        payDetailInfo.setWarId(wd.getId());
                                    }
                                }
                            }
                            if(satisfy){
                                //满足要求，跳出循环
                                break;
                            }
                        }
                        //检查本条入库详情是否成功指定仓库
                        if(satisfy){
                            //满足要求，进行数据添加
                            //根据仓库详情id，获取仓库详情对象
                            WarehouseDetailsInfo temp_obj=warehouseDetailsInfoMapper.selectById(payDetailInfo.getWarId());
                            payDetailInfo.setWarId(temp_obj.getPId());//将仓库详情对象的父id存入属性内
                            queryWrapper=new QueryWrapper<SupplierSupplyOfGoods>();
                            queryWrapper.eq("p_id",temp_obj.getUId());//供应商id，从指定的仓库详情中获取
                            queryWrapper.eq("g_id",od.getGId());//商品id
                            payDetailInfo.setSupplyOrderId(supplierSupplyOfGoodsMapper.selectOne(queryWrapper).getId());
                            payDetailInfo.setShopNum(od.getBuyQuantity());
                            payDetailInfo.setIsDelete(0);
                            //添加出库详情数据
                            payDetailInfoMapper.insert(payDetailInfo);
                            payDetailInfoIds.add(payDetailInfo.getId());
                            //修改订单详情的出库状态和出库详情id
                            od.setIsStorage(1);//出库申请中
                            od.setPdId(payDetailInfo.getId());//出库详情id
                            ordersParticularsMapper.updateById(od);
                            ordersParticularsIds.add(od.getId());
                        }else {
                            //未成功，终止循环
                            allSpecified=true;
                            break;
                        }
                    }
                    //检查中途是否遇到仓库当前库存不足或所有仓库不存在该商品导致无法全部指定仓库
                    if(allSpecified){
                        //中途遇到仓库数量不足，设置提示信息和未满足要求的订单
                       // map.put("msg","本次要出库的多个订单，出现仓库货物不足，未满足出库要求的订单如下↓");
                        map.put("msg","本次要出库的多个订单，出现仓库货物不足");
                        map.put("x",false);
//                        map.put("list",false);//【弹出对话框，给用户观看】
                        //删除入库表和入库详情表
                        if(payInfoInfoIds.size()>0){
                            payInfoMapper.deleteBatchIds(payInfoInfoIds);
                        }
                        if(payDetailInfoIds.size()>0){
                            payDetailInfoMapper.deleteBatchIds(payDetailInfoIds);
                        }
                        //重新恢复订单详情的出库详情id
                        if(ordersParticularsIds.size()>0){
                            for(Integer oid : ordersParticularsIds){
                                UpdateWrapper updateWrapper=new UpdateWrapper<OrdersParticulars>();
                                updateWrapper.eq("id",oid);
                                updateWrapper.set("pd_id",null);
                                ordersParticularsMapper.update(new OrdersParticulars(),updateWrapper);
                            }
                        }
                        //将ids内的订单的货物状态设置为【用户等待提货，等待总店发货到商户】，最后终止循环
                        for(Integer temp_id : ids){
                            Orders temp_orders=ordersMapper.selectById(temp_id);
                            temp_orders.setGoodsState("g-1");
                            ordersMapper.updateById(temp_orders);
                        }
                        break;
                    }else {
                        //没有出现货物不足的情况
                        map.put("msg","已经全部发起出库申请，等待审核");
                        map.put("x",true);
                    }
                }else {
                    map.put("msg","操作错误");
                    map.put("x",false);
                }
            }
        }else {
            map.put("msg","该商户没有需要出库的订单");
            map.put("x",false);
        }
        return map;
    }

    @Override
    public Map audit(PayInfo payInfo) {
        Map map=new HashMap<String,Object>();
        //获取审核结果
        Integer result=payInfo.getIsCheck();
        //获取出库表对象
        payInfo=payInfoMapper.selectById(payInfo.getId());
        //获取出库详情数据
        QueryWrapper queryWrapper=new QueryWrapper<PayDetailInfo>();
        queryWrapper.eq("pay_id",payInfo.getId());
        List<PayDetailInfo> payDetailInfoList=payDetailInfoMapper.selectList(queryWrapper);
        //检查审核结果
        if(result==1){
            //允许通过
            //修改审核状态
            payInfo.setIsCheck(result);
            if(payInfoMapper.updateById(payInfo)>0){
                map.put("msg","审核通过");
                map.put("x",true);
            }else {
                map.put("msg","操作错误");
                map.put("x",false);
            }
            //循环出库详情，为每一个出库详情对应的仓库属性列的真实库存进行修改
            for(PayDetailInfo p : payDetailInfoList){
                queryWrapper=new QueryWrapper<WarehouseDetailsInfo>();
                //获取商品维护表数据
                p.setSupplierSupplyOfGoods(supplierSupplyOfGoodsMapper.selectById(p.getSupplyOrderId()));
                queryWrapper.eq("p_id",p.getWarId());
                queryWrapper.eq("shop_id",p.getSupplierSupplyOfGoods().getGId());
                //查找仓库详情表
                WarehouseDetailsInfo warehouseDetailsInfo=warehouseDetailsInfoMapper.selectOne(queryWrapper);
                //根据仓库详情表数据，对真实库存进行修改
                //【真实库存=当前真实库存-出库详情的出库商品数量】
                warehouseDetailsInfo.setAmount(warehouseDetailsInfo.getAmount()-p.getShopNum());
                //由于出库申请未做锁定库存的修改，这里统一修改【以后需要补上，要在申请时修改锁定库存，现在由于时间问题未做修改】
                warehouseDetailsInfo.setLockStock(warehouseDetailsInfo.getLockStock()-p.getShopNum());
                warehouseDetailsInfoMapper.updateById(warehouseDetailsInfo);
            }
            //获取订单对象
            queryWrapper=new QueryWrapper<Orders>();
            queryWrapper.eq("p_id",payInfo.getTrackingNumber());
            Orders orders=ordersMapper.selectOne(queryWrapper);
            //将订单的货物状态设置为待提货
            orders.setOrderState("o-2");
            //将订单的货物状态设置为【总店发货，等待商户接收】
            orders.setGoodsState("g-3");
            ordersMapper.updateById(orders);
            //获取订单详情对象集合
            queryWrapper=new QueryWrapper<OrdersParticulars>();
            queryWrapper.eq("p_id",orders.getId());//父id
            queryWrapper.eq("is_return",0);//未退货的订单详情
            List<OrdersParticulars> ordersParticularsList=ordersParticularsMapper.selectList(queryWrapper);
            //循环订单详情对象
            for(OrdersParticulars o : ordersParticularsList){
                //将出库状态设置为已出库
                o.setIsStorage(2);
                ordersParticularsMapper.updateById(o);
            }
        }else {
            //拒绝通过
            //修改审核状态
            payInfo.setIsCheck(result);
            if(payInfoMapper.updateById(payInfo)>0){
                map.put("msg","拒绝通过");
                map.put("x",true);
            }else {
                map.put("msg","操作错误");
                map.put("x",false);
            }
            //循环出库详情，为每一个出库详情对应的仓库属性列的锁定库存进行修改
            for(PayDetailInfo p : payDetailInfoList){
                queryWrapper=new QueryWrapper<WarehouseDetailsInfo>();
                //获取商品维护表数据
                p.setSupplierSupplyOfGoods(supplierSupplyOfGoodsMapper.selectById(p.getSupplyOrderId()));
                queryWrapper.eq("p_id",p.getWarId());
                queryWrapper.eq("shop_id",p.getSupplierSupplyOfGoods().getGId());
                //查找仓库详情表
                WarehouseDetailsInfo warehouseDetailsInfo=warehouseDetailsInfoMapper.selectOne(queryWrapper);
//                //根据仓库详情表数据，对锁定库存进行修改
//                //【锁定库存=当前锁定库存+出库详情的出库商品数量】
//                warehouseDetailsInfo.setLockStock(warehouseDetailsInfo.getLockStock()+p.getShopNum());
//                warehouseDetailsInfoMapper.updateById(warehouseDetailsInfo);
            }
            //是订单，获取订单对象
            queryWrapper=new QueryWrapper<Orders>();
            queryWrapper.eq("p_id",payInfo.getTrackingNumber());
            Orders orders=ordersMapper.selectOne(queryWrapper);
            //将订单的货物状态设置为【用户等待提货，等待总店发货到商户】
            orders.setGoodsState("g-1");
            ordersMapper.updateById(orders);
            //获取订单详情对象集合
            queryWrapper=new QueryWrapper<OrdersParticulars>();
            queryWrapper.eq("p_id",orders.getId());//父id
            queryWrapper.eq("is_return",0);//未退货的订单详情
            List<OrdersParticulars> ordersParticularsList=ordersParticularsMapper.selectList(queryWrapper);
            //循环订单详情对象
            for(OrdersParticulars o : ordersParticularsList){
                //将出库状态设置为未出库【这样就可以重新进行出库申请了】
                o.setIsStorage(0);
                ordersParticularsMapper.updateById(o);
            }
        }
        System.out.println("审核结果："+result);
        return map;
    }
}
